package com.sinbad.fileupload.controller;

import com.sinbad.fileupload.entity.Message;
import com.sinbad.fileupload.entity.UploadFile;
import com.sinbad.fileupload.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author: sinbad
 * @time: 2021/10/22
 * @description：
 */
@RestController
@RequestMapping("file")
public class FileUploadController {

    @Autowired
    FileStorageService fileStorageService;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResponseEntity upload(@RequestParam("file") MultipartFile file) {
        try {
            //上传文件资源
            fileStorageService.save(file);
            //返回资源URL地址
            String url = MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
                    "getFile", file.getOriginalFilename()).build().toString();
            return ResponseEntity.ok(url);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new Message("Could not upload the file:" + file.getOriginalFilename()));
        }
    }

    /**
     * 获取上传文件资源列表
     *
     * @return
     */
    @GetMapping("/files")
    public List<UploadFile> getUploadFiles() {
        List<UploadFile> files = fileStorageService.load().map(path -> {
            String fileName = path.getFileName().toString();
            String url = MvcUriComponentsBuilder
                    .fromMethodName(FileUploadController.class,
                            "getFile",
                            path.getFileName().toString()
                    ).build().toString();
            return new UploadFile(fileName, url);
        }).collect(Collectors.toList());
        return files;
    }


    /**
     * 下载某个文件
     *
     * @param filename
     * @return
     */
    @GetMapping("/files/{filename:.+}")
    public ResponseEntity<Resource> getFile(@PathVariable("filename") String filename) {
        Resource file = fileStorageService.load(filename);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment;filename=\"" + file.getFilename() + "\"")
                .body(file);
    }
}
